package com.lovegu.netty.client;

import com.lovegu.netty.res.RpcResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.AttributeKey;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author 老顾 1437594522@qq.com
 * @description
 * @date 2022/11/23 9:23
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg){
        try {
            RpcResponse rpcResponse = (RpcResponse) msg;
            System.out.println("客户端接收消息："+rpcResponse.toString());
            //声明一个AttributeKey对象
            AttributeKey<RpcResponse> key = AttributeKey.valueOf("rpcResponse");
            //将服务端的返回结果保存到AttributeMap | AttributeMap 可以看作是一个channel的共享数据源
            ctx.channel().attr(key).set(rpcResponse);
            ctx.channel().close();
        }finally {
            //释放对象
            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause){
        System.out.println("客户端导致的异常："+ cause.toString());
        ctx.close();
    }
}
